package org.tigris.atlas.quizme.client.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.tigris.atlas.quizme.client.utils.ClientUtils;
import org.tigris.atlas.quizme.client.utils.Constants;
import org.tigris.atlas.quizme.service.QuizCollectionServiceResponse;
import org.tigris.atlas.quizme.service.delegate.QuizServiceDelegate;
import org.tigris.atlas.quizme.service.delegate.ServiceDelegateFactory;
import org.tigris.atlas.quizme.transfer.UserProfile;

/**
 * Searches for past quizzes performed by the logged in user.
 * 
 * @author Robert Simmering
 */
public class SearchQuizHistoryAction  extends Action {
	public ActionForward execute(ActionMapping mapping, ActionForm form,
		      HttpServletRequest request, HttpServletResponse response) {	
		UserProfile userProfile = (UserProfile)request.getSession().getAttribute(Constants.USER_KEY);
		
		// Use the generated QuizServiceDelegate to execute the DB query
		QuizServiceDelegate sd = ServiceDelegateFactory.createQuizServiceDelegate();
		QuizCollectionServiceResponse quizResponse = sd.selectAllQuizzesForUser(userProfile.getId());
		if(quizResponse.getMessages().hasErrorMessages()){
			ClientUtils.getMessagesHandler().handleMessages( quizResponse.getMessages(), null, request);
			return mapping.findForward("fail");
		}
		
		request.getSession().setAttribute(Constants.QUIZ_HISTORY_KEY, quizResponse.getItems());
		return mapping.findForward("success");
	}
}
